package sdk

import (
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"likeadmin/core"
	"likeadmin/core/response"
	"likeadmin/util"
	"mime/multipart"
	"path"
)

var AliYunOss = aliYunOss{}

type aliYunOss struct{}

func (ali aliYunOss) initOssClient() (bucket *oss.Bucket, err error) {
	conf := util.SettingUtil.GetStorageEngineConf("aliyun")

	client, err := oss.New(conf.Endpoint, conf.AccessKey, conf.SecretKey)
	if err != nil {
		core.Logger.Errorf("storageDriver.aliyunUpload Open err: err=[%+v]", err)
		return nil, response.Failed.Make("OSS 初始化阿里云失败!")
	}

	// 获取存储空间。
	bucket, err = client.Bucket(conf.Bucket)
	return
}

func (ali aliYunOss) Upload(file *multipart.FileHeader, key string, folder string) (err error) {
	bucket, err := ali.initOssClient()
	if err != nil {
		return
	}

	objectName := path.Join(folder, key)

	// 读取文件流
	src, err := file.Open()
	if err != nil {
		return
	}
	defer src.Close()

	err = bucket.PutObject(objectName, src)
	return
}

func (ali aliYunOss) Delete(objectName string) (err error) {
	bucket, err := ali.initOssClient()
	if err != nil {
		return
	}
	err = bucket.DeleteObject(objectName)
	return
}
